package com.zhaopin.theswordreferstooffer;

/**
 * @author yin.peide
 * @date 2021-06-10 14:24
 * 面试题19： 二叉树的镜像
 */
public class Offer19 {

    public static void main(String[] args) {
        //初始化一棵二叉树
        TreeNode treeNode8 = new TreeNode(8);
        TreeNode treeNode6 = new TreeNode(6);
        TreeNode treeNode10 = new TreeNode(10);
        TreeNode treeNode5 = new TreeNode(5);
        TreeNode treeNode7 = new TreeNode(7);
        TreeNode treeNode9 = new TreeNode(9);
        TreeNode treeNode11 = new TreeNode(11);

        treeNode6.setLeft(treeNode5);
        treeNode6.setRight(treeNode7);

        treeNode10.setLeft(treeNode9);
        treeNode10.setRight(treeNode11);

        treeNode8.setLeft(treeNode6);
        treeNode8.setRight(treeNode10);

        //初始化的一个二叉树
        //treeNode8
        preOrderTree(treeNode8);
        System.out.println();
        mirrorImage(treeNode8);
        System.out.println();
        preOrderTree(treeNode8);
        System.out.println();
    }

    /**
     * 递归前序遍历
     *
     * @param treeNode
     */
    public static void preOrderTree(TreeNode treeNode) {
        if (treeNode != null) {
            System.out.print(treeNode.getValue() + " ");
            preOrderTree(treeNode.getLeft());
            preOrderTree(treeNode.getRight());
        }
    }

    public static void mirrorImage(TreeNode treeNode) {
        if (treeNode != null) {
            if (treeNode.getLeft() != null && treeNode.getRight() != null) {
                TreeNode tmpLeft = treeNode.getLeft();
                TreeNode tmpRight = treeNode.getRight();
                treeNode.setLeft(tmpRight);
                treeNode.setRight(tmpLeft);
            }

            if (treeNode.getLeft() != null && treeNode.getRight() == null) {
                TreeNode tmpLeft = treeNode.getLeft();
                treeNode.setRight(tmpLeft);
            }

            if (treeNode.getLeft() == null && treeNode.getRight() != null) {
                TreeNode tmpRight = treeNode.getRight();
                treeNode.setLeft(tmpRight);
            }

            mirrorImage(treeNode.getLeft());
            mirrorImage(treeNode.getRight());
        }
    }


}



